var express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

//
const uploadDir = path.join(__dirname, '../uploads')

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
      cb(null, uploadDir)
  },
  filename: function (req, file, cb) {
      const filename = Date.now() + '-' + file.originalname;
      cb(null, filename);
  }
});
const upload = multer({ storage: storage });

// 确保上传目录存在
if (!fs.existsSync(uploadDir)){
  fs.mkdirSync(uploadDir);
}

var router = express.Router();

let uploadsHistory = [];

/* GET home page. */
router.get('/', function(req, res, next) {
  //res.render('index', { title: 'Express' });
  res.render('main', {uploadsHistory})
});

// 处理文字上传
router.post('/share-text', express.urlencoded({ extended: true }), (req, res) => {
  const { text } = req.body;
  if (!text) {
      return res.status(400).json({ message: 'Text content is required' });
  }

  const filename = `text-${Date.now()}.txt`;
  const filePath = path.join(uploadDir, filename);

  fs.writeFileSync(filePath, text, 'utf8');

  // 添加到上传历史记录中，并保存文本内容
  uploadsHistory.push({ type: 'text', filename, filePath, content: text });
  res.redirect('/');
});


// 处理文件上传
router.post('/share-file', upload.single('file'), (req, res) => {
  if (!req.file) {
      return res.status(400).json({ message: 'File is required' });
  }

  uploadsHistory.push({ type: 'file', filename: req.file.filename, filePath: req.file.path });
  res.redirect('/');
});

// 提供文件下载服务
router.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(uploadDir, filename);

  if (fs.existsSync(filePath)) {
      res.download(filePath);
  } else {
      res.status(404).json({ message: 'File not found' });
  }
});


module.exports = router;
